package com.masc.gurr.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class AccountMap {
	private Map<String, Account> fMapUinAccount;
	
	public AccountMap() {
		fMapUinAccount = new HashMap<String, Account>();
	}
	
	public void addAccount(ProtocolType pType, String pStrUin) {
		fMapUinAccount.put(pStrUin,
				new Account(pType, pStrUin));
		if (!fMapUinAccount.containsKey("selected"))
			selectAccount(pStrUin);
	}
	
	public void addAccount(ProtocolType pType, String pStrUin, String pStrPass) {
		if (fMapUinAccount.containsKey(pStrUin)) { /* update ex. account */
			fMapUinAccount.get(pStrUin).setPass(pStrPass);
		}
		else {
			fMapUinAccount.put(pStrUin,
					new Account(pType, pStrUin, pStrPass));
			if (!fMapUinAccount.containsKey("selected"))
				selectAccount(pStrUin);
		}
	}
	
	public void addAccount(ProtocolType pType, String pStrUin, String pStrPass, String pStrAlias) {
		fMapUinAccount.put(pStrUin,
				new Account(pType, pStrUin, pStrPass, pStrAlias));
		if (!fMapUinAccount.containsKey("selected"))
			selectAccount(pStrUin);
	}
	
	public Account getAccount(String pStrUin) {
		return fMapUinAccount.get(pStrUin);
	}
	
	public Iterator<Account> getAllAccounts() {
		ArrayList<Account> lstA = new ArrayList<Account>();
		Iterator<String> itK = fMapUinAccount.keySet().iterator();
		while (itK.hasNext()) {
			String key = (String) itK.next();
			if (! key.equals("selected"))
				lstA.add(fMapUinAccount.get(key));
		}
		return lstA.iterator();
	}
	
	public void removeAccount(String pStrUin) {
		Account account = fMapUinAccount.get(pStrUin);
		fMapUinAccount.remove(pStrUin);
		if (fMapUinAccount.get("selected").equals(account)) {
			if (fMapUinAccount.keySet().iterator().hasNext())
				selectAccount(fMapUinAccount.keySet().iterator().next());
			else
				fMapUinAccount.remove("selected");
		}
		
	}
	
	public void selectAccount(String pStrUin) {
		if (fMapUinAccount.containsKey(pStrUin)) {
			fMapUinAccount.put("selected", fMapUinAccount.get(pStrUin));
		}
	}
	
	public Account getSelectedAccount() {
		return fMapUinAccount.get("selected");
	}
}
